/*
 * MIT License
 *
 * Copyright (c) 2020 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.postman;

import cn.seaboot.common.core.CommonUtils;
import cn.seaboot.postman.analyzer.ControllerInfo;
import cn.seaboot.postman.root.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 主要用于黑白名单过滤
 * <p>
 * Api loader, get api from Controller-Class.
 * Maybe this Class can be divided into some smaller Class and provide interface for developer in next version.
 *
 * @author Mr.css
 * @date 2020-01-26 10:10
 */
public class ApiLoader {
    private Logger logger = LoggerFactory.getLogger(ApiLoader.class);
    /**
     * 路径匹配校验
     */
    private final AntPathMatcher matcher = new AntPathMatcher(".");

    /**
     * 配置信息
     */
    private PostmanConfiguration configuration;
    /**
     * 白名单，接受此类的Class，优先检测白名单
     */
    private String[] include;
    /**
     * 黑名单，拒绝此类的Class
     */
    private String[] exclusive;

    public void setConfiguration(PostmanConfiguration configuration) {
        this.configuration = configuration;
        this.exclusive = configuration.getExclusive();
        this.include = configuration.getInclude();
    }


    /**
     * Get api form a controller.
     * A Controller can get one or more api-group, because a Controller can map to any url.
     * If the number of {@link RequestMapping#value()} is bigger than 1, will get more api-group.
     * The number {@link RequestMapping#value()} is the same as number of api-group.
     *
     * @param clazz controller' Class
     * @return List<Item>
     */
    List<Item> searchApi(Class<?> clazz) {
        if (isAcceptClass(clazz)) {
            RequestMapping requestMapping = clazz.getDeclaredAnnotation(RequestMapping.class);
            if (requestMapping != null) {
                logger.debug("OpenAPI start search API：" + clazz);
                ControllerInfo controllerInfo = new ControllerInfo(clazz, requestMapping);
                if (!controllerInfo.getMethodInfos().isEmpty()) {
                    return configuration.searchApiFromController(controllerInfo);
                }
            }
        }
        return null;
    }


    /**
     * ignore some Class, checked by {@link String#startsWith(String)} and {@link AntPathMatcher}.
     *
     * @param clazz Class
     * @return boolean
     */
    private boolean isAcceptClass(Class<?> clazz) {
        String className = clazz.getName();
        if (CommonUtils.isNotEmpty(include)) {
            for (String str : include) {
                if (matcher.match(str, className)) {
                    return true;
                }
            }
        }
        if (CommonUtils.isNotEmpty(exclusive)) {
            for (String str : exclusive) {
                if (className.startsWith(str) || matcher.match(str, className)) {
                    return false;
                }
            }
        }
        return true;
    }
}
